// src\router\index.ts
import { createRouter, createWebHashHistory, RouteRecordRaw } from "vue-router";
import AppLayout from "@/layout/AppLayout.vue";
import useUserStore from "@/store/user";

const routes: Array<RouteRecordRaw> = [
  {
    path: "/",
    component: AppLayout,
    children: [
      {
        path: "",
        name: "home",
        component: () =>
          import(/* webpackChunkNmae: "home" */ "@/views/home/index.vue"),
      },
    ],
  },
  {
    path: "/login",
    name: "login",
    component: () =>
      import(/* webpackChunkNmae: "login" */ "@/views/login/index.vue"),
  },
  {
    path: "/profile",
    name: "profile",
    component: () =>
      import(/* webpackChunkNmae: "profile" */ "@/views/profile/index.vue"),
    meta: { requireAuth: true },
  },
];

const router = createRouter({
  history: createWebHashHistory(),
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requireAuth)) {
    const userStore = useUserStore();
    const token = userStore.token;
    console.log("🚀 ~ router.beforeEach ~ token:", token);
    if (!token) {
      next({
        path: "/login",
        query: { redirect: to.fullPath },
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
